<template>
  <div>
    <el-upload
      :accept="upload.exts"
      :action="upload.url"
      :auto-upload="true"
      :data="upload.data"
      :file-list="upload.fileList"
      :headers="upload.headers"
      :on-preview="handleFilePreview"
      :on-progress="handleFileUploadProgress"
      :on-remove="handleFileRemove"
      :before-upload="handleBeforeUpload"
      :on-success="handleFileSuccess"
      :on-error="handleFileError"
      :disabled="disabled"
      ref="upload">
      <el-button :disabled="disabled" size="small" slot="trigger" type="primary">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { delAttachment, listByBusinessKeyAndUploaderId } from '../../api/enterprise/attachment'

  export default {
    name: 'Attachment',
    props: {
      disabled: {
        required: false,
        type: Boolean,
        default: false
      },
      accept: {
        required: false,
        type: String
      },
      moduleName: {
        required: false,
        type: String
      },
      businessId: {
        required: false,
        type: Number
      },
      uploaderId: {
        required: false,
        type: String
      },
      onFileSuccess: {
        required: false,
        type: Function
      },
      uploadSizeLimit: {
        required: false,
        type: Number,
        default: 10
      }
    },
    data() {
      return {
        //上传的附件ID拼接的字符串，新增时使用
        uploadAttachmentIds: '',
        // 上传参数
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/enterprise/attachment/upload',
          // 上传的文件列表
          fileList: [],
          // 接受的格式
          exts: '.jpg,.png,.gif,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt',
          // 上传附带的数据
          data: {
            moduleName: this.moduleName,
            uploaderId: this.uploaderId,
            businessKey: this.uploaderId + this.businessId
          }
        }
      }
    },
    created() {
      //重置接收文件格式
      if (this.accept) {
        this.upload.exts = this.accept
      }
    },
    methods: {
      /**初始化文件队列*/
      initFileList() {
        if (this.businessId && this.upload.data.uploaderId) {
          listByBusinessKeyAndUploaderId(this.businessId, this.upload.data.uploaderId).then(response => {
            this.upload.fileList = response.map(element => {
              return {
                status: 'success',
                name: element.originalName,
                size: element.fileSize,
                percentage: 100,
                response: {
                  attachmentId: element.id,
                  fileName: element.fileName,
                  url: process.env.VUE_APP_BASE_API + element.fileName
                }

              }
            })
          })
        }
      },
      // 文件上传前处理
      handleBeforeUpload(file) {
        // 上传大小检查，以M为单位
        const uploadSizeLimit = this.uploadSizeLimit * 1024 * 1024
        if (!file || file && file.size > uploadSizeLimit) {
          this.msgError('上传文件大小不能大于10M')
          return false
        }

        // 上传类型检查 todo mine映射

      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        if (response.code === 200) {
          this.upload.isUploading = false

          if (this.uploadAttachmentIds) {
            this.uploadAttachmentIds += ',' + response.attachmentId
          } else {
            this.uploadAttachmentIds = response.attachmentId
          }

          //处理文件队列里面url的基础路径
          this.upload.fileList = fileList.map(item => {
            item.response.url = process.env.VUE_APP_BASE_API + item.response.fileName
            return item
          })

          this.$emit('onFileSuccess', this.uploadAttachmentIds)
          this.msgSuccess(response.msg)
        } else {
          this.msgError(response.msg)
        }

      },
      //文件上传失败
      handleFileError(err, file, fileList) {
        this.msgError('上传错误')
      },
      // 文件删除处理
      handleFileRemove(file, fileList) {
        if (file && file.response) {
          let attachmentId = parseInt(file.response.attachmentId)
          delAttachment(attachmentId).then(response => {
            this.msgSuccess(response.msg)
          })
        }
      },
      //文件预览
      handleFilePreview(file) {
        if (file && file.response) {
          window.open(file.response.url)
        }
      },
      //清空队列
      clearFiles() {
        this.uploadAttachmentIds = ''
        this.$refs.upload.clearFiles()
      },
      //设置businessId
      setBusinessId(businessId) {
        this.upload.data.businessKey = this.uploaderId + businessId
      }
    }
  }
</script>

<style scoped>
</style>
